package com.web.server;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;


@WebServlet(urlPatterns = "/login")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String againPass = req.getParameter("againPass");
        String address = req.getParameter("address");
        if (password.equals(againPass)) {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                String url = "jdbc:mysql://127.0.0.1:3306/demo";
                Connection conn = DriverManager.getConnection(url, "root", "root");

                PreparedStatement stmt01 = conn.prepareStatement("select*from users where username=?");
                stmt01.setString(1, userName);
                ResultSet rs = stmt01.executeQuery();
                if (rs.next()) {
                    resp.getWriter().write("此账号已存在请重新输入");
                }else {
                    PreparedStatement stmt02 = conn.prepareStatement
                            ("insert into users(username,password,address) values(?,?,?)");
                    stmt02.setString(1, userName);
                    stmt02.setString(2, password);
                    stmt02.setString(3, address);
                    int i = stmt02.executeUpdate();
                    if (i>0){
                        resp.getWriter().write("注册成功");
                    }else {
                        System.out.println("注册失败");
                    }
                    stmt02.close();
                }

                stmt01.close();
                conn.close();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        }else {
            resp.getWriter().write("两次输入密码不一致，注册失败");
        }

    }
}
